const Purposes = require("../models/purposes")
class PurposesCtrl {

    async checkPurposesExist(ctx) {
        const purposes = await Purposes.findById(ctx.params.id)
        if (!purposes) {
            ctx.throw(404, '用途不存在')
        }
    }

    async find(ctx) {
        let { per_page = 2, q = '' } = ctx.query
        let page = Math.max(ctx.query.page * 1, 1) - 1
        let perPage = Math.max(per_page * 1, 1)
        ctx.body = Purposes
            .find({ name: new RegExp(q) })
            .limit(perPage)
            .skip(page * perPage)
    }

    async findById(ctx) {
        const purposes = await Purposes.findById(ctx.params.id)
        ctx.body = purposes
    }

    async create(ctx) {
        ctx.verifyParams({
            name: {
                type: 'string',
                required: true
            },
            remark: {
                type: 'string',
                required: false
            },
        })
        const { name } = ctx.request.body
        const repeatedPurposes = await Purposes.findOne({ name })
        if (repeatedPurposes) {
            ctx.throw(409, '用途已存在')
        }
        const purposes = await new Purposes(ctx.request.body).save()
        ctx.body = purposes
    }

    async update(ctx) {
        ctx.verifyParams({
            name: {
                type: 'string',
                required: true
            },
            remark: {
                type: 'string',
                required: false
            },
        })
        const purposes = await Purposes.findByIdAndUpdate(ctx.params.id, ctx.request.body)
        ctx.body = purposes
    }

    async delete(ctx) {
        await Purposes.findByIdAndDelete(ctx.params.id, ctx.request.body)
        ctx.status = 204
    }
}

module.exports = new PurposesCtrl()